package com.yimi.yinhepda.views.login.logic;

import android.content.Context;
import android.util.Log;

import com.pda.uce.commom.util.LoadUtils;
import com.pda.ym.utils.SysInfo;
import com.uce.pda.MyAppLication;
import com.yimi.yinhepda.base.BaseActivity2;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.entity.bean.LoginInfoEntity;
import com.yimi.yinhepda.entity.response.BooleanDataResponse;
import com.pda.ym.net.NetRequest;
import com.pda.ym.utils.AppInfoHelper;
import com.yimi.yinhepda.utils.CheckNetTimeUtil;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.NetworkUtil;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.yimi.yinhepda.views.login.contract.LoginContract;
import com.yimi.yinhepda.views.login.model.Login;
import com.yimi.yinhepda.views.login.model.request.LoginLogRequest;
import com.yimi.yinhepda.views.login.model.request.LoginRequest;
import com.yimi.yinhepda.views.login.model.respones.CompanyFindAllResponse;
import com.yimi.yinhepda.views.login.model.respones.LoginLogResponse;
import com.yimi.yinhepda.views.login.model.respones.LoginResponse;
import com.yimi.yinhepda.views.login.presenter.LoginPresenter;

import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 000432
 */
public class LoginLogic extends UICallBack implements LoginContract.LoginBiz {

    private LoginPresenter mPresenter;
    private String mCompanyCode;
    private String mEmpCode;
    private String mPwd;
    private String mCaptcha;
    private SharedPreferUtil sharedPreferUtil;
    private boolean mNeedVcode;

    public LoginLogic(LoginPresenter mPresenter) {
        this.mPresenter = mPresenter;
        sharedPreferUtil = ((BaseActivity2) getContext()).getSharedPreferUtil();
    }

    @Override
    public Context getContext() {
        return mPresenter.getContext();
    }

    @Override
    public void onError(String msg) {
    }

    @Override
    public void onError(String msg, Object obj) {
        LoadUtils.hideLoading(getContext());
        SoundVibratorManager.playSound(2);
        ((BaseActivity2) getContext()).showToast(msg);
        if (obj instanceof LoginResponse) {
            //请求是否需要验证码
            checkNeedCaptchaRequest();
        } else if (obj instanceof InputStream) {
            mPresenter.getReference().noNeedCaptchaImage();
        }
    }

    @Override
    public void onSuccess(Object obj) {
        LoadUtils.hideLoading(getContext());
        if (obj instanceof CompanyFindAllResponse) {
            CompanyFindAllResponse response = (CompanyFindAllResponse) obj;
            mPresenter.getReference().getCompanyInfoSuccess(response.getData());
        } else if (obj instanceof LoginResponse) {
            LoginResponse loginResponse = (LoginResponse) obj;
            Login mLogin = loginResponse.getData();
            Log.d("TAG", "onResponse: 用户userCode=" + loginResponse.getData().getUserCode());
            if ("admin".equals(mLogin.getJob())) {
                //限制超级管理员登录PDA
                ((BaseActivity2) getContext()).showToast("超级管理员不可登录！");
                return;
            }

            sharedPreferUtil.setWorkNum(mEmpCode);
            mLogin.setUserWorkNum(mEmpCode);

            //上传PDA后台管理登录信息
            uploadPdaManagerLogInfo(mLogin);

            //设置登录信息存入文件
            sharedPreferUtil.setValue(Common.JOB, mLogin.getJob());
            // 部门类型: 2,3,4分别是一级网点，二级网点，三级网点; 5,6分别是一级分拨，二级分拨
            sharedPreferUtil.setIntValue(Common.DEPT_TYPE, mLogin.getDeptType());
            sharedPreferUtil.setValue(Common.USER_CODE, mLogin.getUserCode());
            sharedPreferUtil.setValue(Common.USER_NAME, mLogin.getUsername());
            sharedPreferUtil.setValue(Common.DEPT_CODE, mLogin.getDeptCode());
            sharedPreferUtil.setValue(Common.DEPT_NAME, mLogin.getDeptName());
            sharedPreferUtil.setValue(Common.COMP_CODE, mLogin.getCompCode());
            sharedPreferUtil.setValue(Common.COMP_NAME, mLogin.getCompName());
            sharedPreferUtil.setEmpName(mLogin.getUsername());
            sharedPreferUtil.setDeptCode(mLogin.getDeptCode());

            String oldServer = sharedPreferUtil.getValue(Common.OLD_SERVER);
            String newServer = sharedPreferUtil.getServerIp();
            if (!oldServer.equals(newServer)) {
                // 设置服务器ip已经改变，方便在mainActivity里面重新获取基础数据
                sharedPreferUtil.setServerIpHaveChanged(true);
            } else {
                sharedPreferUtil.setServerIpHaveChanged(false);
            }
            sharedPreferUtil.setValue(Common.OLD_SERVER, newServer);
            //清除下载的零时文件
            initUpdate();

            if (mPresenter.getReference() != null) {
                mPresenter.getReference().loginSuccess(mPwd);
            }

            //上传登录日志
            uploadLoginLog(mLogin);
        } else if (obj instanceof BooleanDataResponse) {
            BooleanDataResponse response = (BooleanDataResponse) obj;
            boolean data = response.getData();
            if (data) {
                //需要请求验证码，获取验证码图片
                mPresenter.getReference().getCaptchaImage();
            } else {
                mPresenter.getReference().noNeedCaptchaImage();
            }
        }
    }

    /**
     * 请求校验是否需要验证码
     */
    private void checkNeedCaptchaRequest() {
        Map<String, String> params = new HashMap<>();
        params.put("compCode", mCompanyCode);
        params.put("workNum", mEmpCode);
        new NetRequest().setMethod(NetRequest.Method.GET)
                .setUrl(Constants.URL_CHECK_NEED_CAPTCHA)
                .setParams(params)
                .setResponsClazz(BooleanDataResponse.class)
                .execute(this);
    }

    /**
     * 上传PDA后台管理登录信息
     */
    private void uploadPdaManagerLogInfo(Login login) {
        String preDeptCode = sharedPreferUtil.getDeptCode();
        String preDeptName = sharedPreferUtil.getValue(Common.DEPT_NAME);
        //设置上一部门
        sharedPreferUtil.setValue(Common.PRE_DEPT_CODE, preDeptCode);
        sharedPreferUtil.setValue(Common.PRE_DEPT_NAME, preDeptName);

        LoginInfoEntity loginInfoEntity = new LoginInfoEntity();
        loginInfoEntity.setCompCode(login.getCompCode());
        loginInfoEntity.setCompName(login.getCompName());
        // 2,3,4分别是一级网点，二级网点，三级网点; 5,6分别是一级分拨，二级分拨
        int deptType = login.getDeptType();
        if (deptType == 5 || deptType == 6) {
            loginInfoEntity.setDeptType(2);
        } else if (deptType == 2 || deptType == 3 || deptType == 4) {
            loginInfoEntity.setDeptType(1);
        }
        loginInfoEntity.setPreDeptCode(preDeptCode);
        loginInfoEntity.setPreDeptName(preDeptName);
        loginInfoEntity.setCurrentDeptCode(login.getDeptCode());
        loginInfoEntity.setCurrentDeptName(login.getDeptName());
        //设置在线
        loginInfoEntity.setOnLine(1);
        loginInfoEntity.setUserCode(login.getUserCode());
        loginInfoEntity.setUserWorkNum(login.getUserWorkNum());
        loginInfoEntity.setUserName(login.getUsername());
        loginInfoEntity.setLoginLastTime((new Date()).getTime());
        loginInfoEntity.setCurrentPdaVersion(AppInfoHelper.getAppVersion(getContext()));
        loginInfoEntity.setCurrentPdaVersionName(AppInfoHelper.getAppVersionName(getContext()));
        loginInfoEntity.setNewPdaVersion(sharedPreferUtil.getIntValue(Constants.NEW_PAD_VERSION));
        loginInfoEntity.setNewPdaVersoinName(sharedPreferUtil.getValue(Constants.NEW_PDA_VERSION_NAME));
        loginInfoEntity.setPdaBrand(SysInfo.getInstance().getManufacturer());
        loginInfoEntity.setPdaModel(SysInfo.getInstance().getPhoneModel());
        loginInfoEntity.setDevId(SysInfo.getInstance().getImei());
        loginInfoEntity.setMacAddress(SysInfo.getInstance().getMacAddr());
        loginInfoEntity.setDevOsVersion(SysInfo.getInstance().getOsVersion());

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(Object.class)
                .setUrl(Constants.URL_PDA_MANAGER_LOGIN_INFO)
                .setRequestObject(loginInfoEntity)
                .setConnTimeOut(5L * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                        LogUtil.e(msg);
                    }

                    @Override
                    public void onSuccess(Object obj) {
                    }
                });
    }

    /**
     * 上传登录日志.
     */
    private void uploadLoginLog(Login login) {
        LoginLogRequest loginLogRequest =
                new LoginLogRequest(login.getUserCode(), login.getUsername(), "3", login.getCompCode(), NetworkUtil.getMacAddr());

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(LoginLogResponse.class)
                .setUrl(Constants.LOGIN_LOG_URL)
                .setRequestObject(loginLogRequest)
                .setConnTimeOut(5L * 1000)
                .execute(new UICallBack() {
                    @Override
                    public void onError(String msg) {
                    }

                    @Override
                    public void onSuccess(Object obj) {
                        LogUtil.e(obj.toString());
                    }
                });
    }

    /**
     * 校验网络时间
     */
    @Override
    public void checkNetworkTime(final String companyCode, final String empCode, final String pwd, String captcha, boolean needVcode) {
        this.mCompanyCode = companyCode;
        this.mEmpCode = empCode;
        this.mPwd = pwd;
        this.mCaptcha = captcha;
        this.mNeedVcode = needVcode;

        CheckNetTimeUtil.checkNetworkTimeForLogin(getContext(), mCompanyCode, mEmpCode, mPwd, new UICallBack() {
            @Override
            public void onError(String msg) {
            }

            @Override
            public void onSuccess(Object obj) {
                //用户登录请求
                loginRequest(mCompanyCode, mEmpCode, mPwd);
            }
        });
    }

    /**
     * 查询公司名称
     */
    @Override
    public void queryCompany() {
        new NetRequest().setMethod(NetRequest.Method.GET).
                setResponsClazz(CompanyFindAllResponse.class).
                setUrl(Constants.QUERY_COMPANY_NAME).
                setConnTimeOut(10L * 1000).
                execute(this);
    }

    /**
     * 用户登录请求
     */
    private void loginRequest(String mCompanyCode, final String mEmpCode, final String mPwd) {
        String deviceId = SysInfo.getInstance().getImei();
        LoginRequest mLoginRequest = new LoginRequest(mCompanyCode, mEmpCode, mPwd, mCaptcha, mNeedVcode, "3", deviceId);
        LoadUtils.showLoading("登录中，请稍等...",getContext());

        new NetRequest().setMethod(NetRequest.Method.POST_STRING)
                .setResponsClazz(LoginResponse.class)
                .setUrl(Constants.LOGIN_URL)
                .setRequestObject(mLoginRequest)
                .setConnTimeOut(5L * 1000)
                .execute(this);
    }

    /**
     * 因为下载的时候可能下载一半就失败了，这个时候破损的文件已经存在了。
     * 导致更新失败。
     * 1、在登录的时候设置配置文件的版本号和当前程序一致
     * 2、删除下载的更新文件。这样保证每次登录进去就是一个初始状态。
     */
    private void initUpdate() {
        String path = Constants.STROAGEPATH + Constants.APKNAME;
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }
}
